package com.mornd.gulimall.product.service.impl;

import com.mornd.gulimall.product.entity.Attr;
import com.mornd.gulimall.product.entity.SkuInfo;
import com.mornd.gulimall.product.entity.SkuSaleAttrValue;
import com.mornd.gulimall.product.entity.vo.skuitem.ItemSales;
import com.mornd.gulimall.product.entity.vo.skuitem.SkuItemResult;
import com.mornd.gulimall.product.entity.vo.spusave.SaleVo;
import com.mornd.gulimall.product.mapper.SkuSaleAttrValueMapper;
import com.mornd.gulimall.product.service.IAttrService;
import com.mornd.gulimall.product.service.ISkuSaleAttrValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * sku销售属性&值 服务实现类
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */
@Service
public class SkuSaleAttrValueServiceImpl extends ServiceImpl<SkuSaleAttrValueMapper, SkuSaleAttrValue> implements ISkuSaleAttrValueService {
    @Resource
    private IAttrService attrService;

    /**
     * 保存 sku 的销售属性集合
     *
     * @param skus
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSales(List<SkuInfo> skus) {
        List<SkuSaleAttrValue> saves = new ArrayList<>();
        for (SkuInfo sku : skus) {
            List<SaleVo> sales = sku.getSales();
            int sort = 0;
            for (SaleVo sale : sales) {
                SkuSaleAttrValue attrValue = new SkuSaleAttrValue();
                attrValue.setAttrId(sale.getAttrId());
                attrValue.setSkuId(sku.getSkuId());
                attrValue.setAttrValue(sale.getAttrName());
                attrValue.setAttrSort(sort++);

                Attr attr = attrService.getById(sale.getAttrId());
                if(attr != null) {
                    attrValue.setAttrName(attr.getAttrName());
                }

                saves.add(attrValue);
            }
        }

        super.saveBatch(saves);
    }

    /**
     * 根据 spuId 查询其对应的销售属性
     *
     * @param spuId
     * @return
     */
    @Override
    public List<ItemSales> getSalesBySpuId(Long spuId) {
        return baseMapper.getSalesBySpuId(spuId);
    }

    @Override
    public List<String> getSkuSaleStringlist(Long skuId) {
        return baseMapper.getSkuSaleStringlist(skuId);
    }
}
